package com.suliu.practice.io;

import java.io.IOException;
import java.io.InputStream;

public class MyOwnStream {
	public static void main(String[] args) throws IOException {
		byte[] b=new byte[16];
		for(int i=0;i<b.length;i++){
			b[i]=(byte)i;
		}
		MyByteArrayInputStream mbais=new MyByteArrayInputStream(b);
		while(true){
			int c=mbais.read();
			if(c<0)
				break;
			System.out.print(c+" ");
		}
		System.out.println();
	}
}
//实现一个自己的字节输入流
class MyByteArrayInputStream extends InputStream{
	protected byte[] data;
	protected int ptr=0;
	protected int mark=0;
	public MyByteArrayInputStream(byte[] b){
		this.data=b;
	}
	@Override
	public int read() throws IOException {
		//每次读取一个字节返回，没有读到就返回-1
		return (ptr<data.length)?(data[ptr++]):-1;
	}
	@Override
	public int available() throws IOException {
		return data.length-ptr;
	}
	@Override
	public void close() throws IOException {
		ptr=data.length;//模拟，非硬件
	}
	@Override
	public synchronized void mark(int readlimit) {
		this.mark=readlimit;
	}
	@Override
	public synchronized void reset() throws IOException {
		if(mark<0||mark>=data.length){
			throw new IOException("the position is not valid");
		}
		ptr=mark;
	}
	@Override
	public boolean markSupported() {
		return true;
	}
	//重写第三个方法，不用每次读一个字节效率低
	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		if(this.ptr>=data.length ||len<0){
			return -1;
		}
		if((this.ptr+len)>data.length){
			len=data.length-this.ptr;
		}
		if(len==0)return 0;
		System.arraycopy(data, ptr, b, off, len);
		ptr+=len;
		return len;
		//总觉得有问题……
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
